<template>
  <section class="demo-section">
    <div class="demo-header">
      <h2 class="demo-title">5. shallowRef & shallowReactive 浅层响应式 (Vue 3.0+)</h2>
      <p class="demo-description">
        shallowRef 和 shallowReactive 是 Vue 3.0+ 引入的浅层响应式
        API，它们只在根级别提供响应式追踪，
        而不会深度转换嵌套对象。这种设计在处理大型数据结构时能显著提升性能。
      </p>
    </div>

    <div class="demo-content">
      <!-- shallowRef vs ref 对比 -->
      <div class="demo-card">
        <h3 class="card-title">📊 shallowRef vs ref 对比演示</h3>

        <div class="comparison-container">
          <div class="comparison-side">
            <h4>🔍 普通 ref (深层响应式)</h4>
            <div class="state-display">
              <p><strong>当前状态:</strong></p>
              <pre>{{ JSON.stringify(deepState, null, 2) }}</pre>
              <p><strong>更新次数:</strong> {{ deepUpdateCount }}</p>
            </div>

            <div class="controls">
              <button @click="updateDeepRoot" class="btn btn-primary">更新根对象</button>
              <button @click="updateDeepNested" class="btn btn-secondary">
                更新嵌套属性
              </button>
              <button @click="resetDeepState" class="btn btn-outline">重置状态</button>
            </div>
          </div>

          <div class="comparison-side">
            <h4>⚡ shallowRef (浅层响应式)</h4>
            <div class="state-display">
              <p><strong>当前状态:</strong></p>
              <pre>{{ JSON.stringify(shallowState, null, 2) }}</pre>
              <p><strong>更新次数:</strong> {{ shallowUpdateCount }}</p>
            </div>

            <div class="controls">
              <button @click="updateShallowRoot" class="btn btn-primary">
                更新根对象 ✅
              </button>
              <button @click="updateShallowNested" class="btn btn-warning">
                更新嵌套属性 ❌
              </button>
              <button @click="forceShallowUpdate" class="btn btn-success">
                手动触发更新
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- shallowReactive vs reactive 对比 -->
      <div class="demo-card">
        <h3 class="card-title">📋 shallowReactive vs reactive 对比演示</h3>

        <div class="comparison-container">
          <div class="comparison-side">
            <h4>🔍 普通 reactive (深层响应式)</h4>
            <div class="state-display">
              <p><strong>用户信息:</strong></p>
              <div class="user-info">
                <p>姓名: {{ deepUser.profile.name }}</p>
                <p>邮箱: {{ deepUser.profile.email }}</p>
                <p>主题: {{ deepUser.settings.theme }}</p>
                <p>语言: {{ deepUser.settings.language }}</p>
              </div>
              <p><strong>更新次数:</strong> {{ deepReactiveUpdateCount }}</p>
            </div>

            <div class="controls">
              <button @click="updateDeepUserProfile" class="btn btn-primary">
                更新个人信息
              </button>
              <button @click="updateDeepUserSettings" class="btn btn-secondary">
                更新设置
              </button>
            </div>
          </div>

          <div class="comparison-side">
            <h4>⚡ shallowReactive (浅层响应式)</h4>
            <div class="state-display">
              <p><strong>用户信息:</strong></p>
              <div class="user-info">
                <p>姓名: {{ shallowUser.profile.name }}</p>
                <p>邮箱: {{ shallowUser.profile.email }}</p>
                <p>主题: {{ shallowUser.settings.theme }}</p>
                <p>语言: {{ shallowUser.settings.language }}</p>
              </div>
              <p><strong>更新次数:</strong> {{ shallowReactiveUpdateCount }}</p>
            </div>

            <div class="controls">
              <button @click="updateShallowUserProfile" class="btn btn-primary">
                替换 profile 对象 ✅
              </button>
              <button @click="updateShallowUserDirect" class="btn btn-warning">
                直接修改属性 ❌
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 性能对比演示 -->
      <div class="demo-card">
        <h3 class="card-title">🚀 性能对比演示</h3>

        <div class="performance-demo">
          <div class="performance-controls">
            <div class="control-group">
              <label>数据量大小:</label>
              <input
                v-model.number="dataSize"
                type="range"
                min="100"
                max="5000"
                step="100"
                class="slider"
              />
              <span>{{ dataSize }} 项</span>
            </div>

            <div class="button-group">
              <button @click="createDeepData" class="btn btn-primary">
                创建深层响应式数据
              </button>
              <button @click="createShallowData" class="btn btn-success">
                创建浅层响应式数据
              </button>
              <button @click="clearPerformanceData" class="btn btn-outline">
                清空数据
              </button>
            </div>
          </div>

          <div class="performance-results">
            <div class="result-card" v-if="performanceResults.deep">
              <h4>🔍 深层响应式性能</h4>
              <p>创建时间: {{ performanceResults.deep.createTime }}ms</p>
              <p>内存使用: {{ performanceResults.deep.memoryUsage }}MB</p>
              <p>数据项数: {{ performanceResults.deep.itemCount }}</p>
            </div>

            <div class="result-card" v-if="performanceResults.shallow">
              <h4>⚡ 浅层响应式性能</h4>
              <p>创建时间: {{ performanceResults.shallow.createTime }}ms</p>
              <p>内存使用: {{ performanceResults.shallow.memoryUsage }}MB</p>
              <p>数据项数: {{ performanceResults.shallow.itemCount }}</p>
              <div class="improvement" v-if="performanceResults.deep">
                <p class="improvement-text">
                  ⚡ 创建速度提升: {{ calculateImprovement("createTime") }}%
                </p>
                <p class="improvement-text">
                  💾 内存节省: {{ calculateImprovement("memoryUsage") }}%
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 实际应用场景演示 -->
      <div class="demo-card">
        <h3 class="card-title">💡 实际应用场景</h3>

        <div class="use-cases">
          <div class="use-case">
            <h4>📊 大型数据列表</h4>
            <p>适合处理大量数据项，只在整体替换时更新UI</p>
            <div class="demo-area">
              <div class="controls">
                <button @click="loadLargeDataset" class="btn btn-primary">
                  加载大型数据集
                </button>
                <button @click="addItemToDataset" class="btn btn-secondary">
                  添加数据项
                </button>
                <button @click="clearDataset" class="btn btn-outline">清空数据</button>
              </div>
              <div class="data-info">
                <p>数据集大小: {{ largeDataset.length }} 项</p>
                <p>最后更新: {{ lastDatasetUpdate }}</p>
              </div>
            </div>
          </div>

          <div class="use-case">
            <h4>🔧 第三方库集成</h4>
            <p>与外部状态管理库或不可变数据结构配合使用</p>
            <div class="demo-area">
              <div class="controls">
                <button @click="simulateExternalUpdate" class="btn btn-primary">
                  模拟外部库更新
                </button>
                <button @click="resetExternalState" class="btn btn-outline">
                  重置状态
                </button>
              </div>
              <div class="external-state">
                <p>外部库状态: {{ externalLibState?.status }}</p>
                <p>数据版本: {{ externalLibState?.version }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 最佳实践和注意事项 -->
      <div class="demo-card">
        <h3 class="card-title">⚠️ 最佳实践与注意事项</h3>

        <div class="best-practices">
          <div class="practice-section">
            <h4>✅ 适合使用的场景</h4>
            <ul class="practice-list good">
              <li>大型数据集或复杂数据结构</li>
              <li>与第三方库集成</li>
              <li>性能关键的应用场景</li>
              <li>不可变数据模式</li>
              <li>只需要根级别响应式的情况</li>
            </ul>
          </div>

          <div class="practice-section">
            <h4>❌ 不适合使用的场景</h4>
            <ul class="practice-list bad">
              <li>需要深层响应式的表单数据</li>
              <li>小型、简单的响应式对象</li>
              <li>频繁需要更新嵌套属性的场景</li>
              <li>组件内部状态管理</li>
              <li>需要监听深层变化的情况</li>
            </ul>
          </div>

          <div class="practice-section">
            <h4>💡 使用技巧</h4>
            <ul class="practice-list tips">
              <li>使用 triggerRef() 手动触发更新</li>
              <li>配合不可变更新模式使用</li>
              <li>避免混合深浅响应式</li>
              <li>适当使用 readonly() 包装</li>
              <li>在开发环境添加调试信息</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
import { ref, reactive, shallowRef, shallowReactive, triggerRef, watch } from "vue";

// shallowRef vs ref 演示数据
const deepState = ref({
  user: {
    name: "Vue Developer",
    profile: {
      age: 25,
      skills: ["JavaScript", "Vue.js"],
    },
  },
});

const shallowState = shallowRef({
  user: {
    name: "Vue Developer",
    profile: {
      age: 25,
      skills: ["JavaScript", "Vue.js"],
    },
  },
});

const deepUpdateCount = ref(0);
const shallowUpdateCount = ref(0);

// 监听更新次数
watch(deepState, () => deepUpdateCount.value++, { deep: true });
watch(shallowState, () => shallowUpdateCount.value++);

// shallowReactive vs reactive 演示数据
const deepUser = reactive({
  profile: {
    name: "Alice",
    email: "alice@example.com",
  },
  settings: {
    theme: "light",
    language: "zh-CN",
  },
});

const shallowUser = shallowReactive({
  profile: {
    name: "Bob",
    email: "bob@example.com",
  },
  settings: {
    theme: "dark",
    language: "en-US",
  },
});

const deepReactiveUpdateCount = ref(0);
const shallowReactiveUpdateCount = ref(0);

watch(deepUser, () => deepReactiveUpdateCount.value++, { deep: true });
watch(shallowUser, () => shallowReactiveUpdateCount.value++);

// 性能测试相关
const dataSize = ref(1000);
const performanceResults = ref<{
  deep?: { createTime: number; memoryUsage: number; itemCount: number };
  shallow?: { createTime: number; memoryUsage: number; itemCount: number };
}>({});

// 大型数据集演示
const largeDataset = shallowRef<any[]>([]);
const lastDatasetUpdate = ref("");

// 外部库集成演示
const externalLibState = shallowRef<{
  status: string;
  version: number;
  data: any;
} | null>(null);

// shallowRef 操作函数
const updateDeepRoot = () => {
  deepState.value = {
    user: {
      name: "Updated User",
      profile: {
        age: Math.floor(Math.random() * 50) + 20,
        skills: ["Vue.js", "TypeScript", "Node.js"],
      },
    },
  };
};

const updateDeepNested = () => {
  deepState.value.user.profile.age = Math.floor(Math.random() * 50) + 20;
  deepState.value.user.profile.skills.push(`Skill${Date.now()}`);
};

const resetDeepState = () => {
  deepState.value = {
    user: {
      name: "Vue Developer",
      profile: {
        age: 25,
        skills: ["JavaScript", "Vue.js"],
      },
    },
  };
};

const updateShallowRoot = () => {
  shallowState.value = {
    user: {
      name: "Updated Shallow User",
      profile: {
        age: Math.floor(Math.random() * 50) + 20,
        skills: ["Vue.js", "Composition API"],
      },
    },
  };
};

const updateShallowNested = () => {
  // 这个操作不会触发更新
  shallowState.value.user.profile.age = Math.floor(Math.random() * 50) + 20;
  shallowState.value.user.profile.skills.push(`Skill${Date.now()}`);
};

const forceShallowUpdate = () => {
  // 先修改嵌套属性
  shallowState.value.user.profile.age = Math.floor(Math.random() * 50) + 20;
  shallowState.value.user.profile.skills.push(`Skill${Date.now()}`);
  // 然后手动触发更新
  triggerRef(shallowState);
};

// shallowReactive 操作函数
const updateDeepUserProfile = () => {
  deepUser.profile.name = `User${Math.floor(Math.random() * 1000)}`;
  deepUser.profile.email = `user${Math.floor(Math.random() * 1000)}@example.com`;
};

const updateDeepUserSettings = () => {
  deepUser.settings.theme = deepUser.settings.theme === "light" ? "dark" : "light";
  deepUser.settings.language = deepUser.settings.language === "zh-CN" ? "en-US" : "zh-CN";
};

const updateShallowUserProfile = () => {
  // 替换整个 profile 对象，这会触发更新
  shallowUser.profile = {
    name: `ShallowUser${Math.floor(Math.random() * 1000)}`,
    email: `shallow${Math.floor(Math.random() * 1000)}@example.com`,
  };
};

const updateShallowUserDirect = () => {
  // 直接修改属性，这不会触发更新
  shallowUser.profile.name = `DirectUpdate${Math.floor(Math.random() * 1000)}`;
  shallowUser.settings.theme = shallowUser.settings.theme === "light" ? "dark" : "light";
};

// 性能测试函数
const createDeepData = () => {
  const startTime = performance.now();
  const data = reactive({
    items: Array.from({ length: dataSize.value }, (_, i) => ({
      id: i,
      name: `Item ${i}`,
      details: {
        category: `Category ${i % 10}`,
        metadata: {
          created: new Date(),
          tags: [`tag${i}`, `tag${i + 1}`],
        },
      },
    })),
  });
  const endTime = performance.now();

  performanceResults.value.deep = {
    createTime: Math.round(endTime - startTime),
    memoryUsage: Math.round((JSON.stringify(data).length / 1024 / 1024) * 100) / 100,
    itemCount: dataSize.value,
  };
};

const createShallowData = () => {
  const startTime = performance.now();
  const data = shallowReactive({
    items: Array.from({ length: dataSize.value }, (_, i) => ({
      id: i,
      name: `Item ${i}`,
      details: {
        category: `Category ${i % 10}`,
        metadata: {
          created: new Date(),
          tags: [`tag${i}`, `tag${i + 1}`],
        },
      },
    })),
  });
  const endTime = performance.now();

  performanceResults.value.shallow = {
    createTime: Math.round(endTime - startTime),
    memoryUsage: Math.round((JSON.stringify(data).length / 1024 / 1024) * 100) / 100,
    itemCount: dataSize.value,
  };
};

const clearPerformanceData = () => {
  performanceResults.value = {};
};

const calculateImprovement = (metric: "createTime" | "memoryUsage") => {
  const deep = performanceResults.value.deep?.[metric] || 0;
  const shallow = performanceResults.value.shallow?.[metric] || 0;

  if (deep === 0) return 0;

  const improvement = ((deep - shallow) / deep) * 100;
  return Math.round(improvement);
};

// 大型数据集操作
const loadLargeDataset = () => {
  const newData = Array.from({ length: 1000 }, (_, i) => ({
    id: Date.now() + i,
    value: Math.random(),
    timestamp: new Date().toISOString(),
  }));

  largeDataset.value = newData;
  lastDatasetUpdate.value = new Date().toLocaleTimeString();
};

const addItemToDataset = () => {
  const newItem = {
    id: Date.now(),
    value: Math.random(),
    timestamp: new Date().toISOString(),
  };

  // 使用不可变更新模式
  largeDataset.value = [...largeDataset.value, newItem];
  lastDatasetUpdate.value = new Date().toLocaleTimeString();
};

const clearDataset = () => {
  largeDataset.value = [];
  lastDatasetUpdate.value = new Date().toLocaleTimeString();
};

// 外部库集成模拟
const simulateExternalUpdate = () => {
  const mockExternalState = {
    status: ["idle", "loading", "success", "error"][Math.floor(Math.random() * 4)],
    version: Date.now(),
    data: {
      users: Array.from({ length: 100 }, (_, i) => ({ id: i, name: `User ${i}` })),
      settings: { theme: "auto", language: "auto" },
    },
  };

  externalLibState.value = mockExternalState;
};

const resetExternalState = () => {
  externalLibState.value = null;
};
</script>

<style scoped>
.demo-section {
  background: white;
  margin-bottom: 3rem;
  border-radius: 16px;
  padding: 2rem;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.05);
}

.demo-header {
  margin-bottom: 2rem;
}

.demo-title {
  font-size: 1.8rem;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 1rem;
}

.demo-description {
  font-size: 1rem;
  color: #64748b;
  line-height: 1.7;
  background: #f8fafc;
  padding: 1rem;
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.demo-content {
  display: grid;
  gap: 2rem;
}

.demo-card {
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  padding: 1.5rem;
  background: #fafbfc;
}

.card-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 1.5rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.comparison-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2rem;
}

.comparison-side {
  background: white;
  padding: 1.5rem;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.comparison-side h4 {
  margin: 0 0 1rem 0;
  color: #374151;
  font-size: 1.1rem;
}

.state-display {
  margin-bottom: 1.5rem;
}

.state-display pre {
  padding: 1rem;
  border-radius: 6px;
  font-size: 0.85rem;
  overflow-x: auto;
  border: 1px solid #e2e8f0;
}

.user-info {
  background: #f1f5f9;
  padding: 1rem;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
}

.user-info p {
  margin: 0.25rem 0;
  color: #374151;
}

.controls {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.btn {
  padding: 0.75rem 1rem;
  border: none;
  border-radius: 6px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 0.9rem;
}

.btn-primary {
  background: #667eea;
  color: white;
}

.btn-primary:hover {
  background: #5a67d8;
}

.btn-secondary {
  background: #6b7280;
  color: white;
}

.btn-secondary:hover {
  background: #4b5563;
}

.btn-warning {
  background: #f59e0b;
  color: white;
}

.btn-warning:hover {
  background: #d97706;
}

.btn-success {
  background: #10b981;
  color: white;
}

.btn-success:hover {
  background: #059669;
}

.btn-outline {
  background: transparent;
  color: #6b7280;
  border: 2px solid #e2e8f0;
}

.btn-outline:hover {
  background: #f9fafb;
  border-color: #d1d5db;
}

.performance-demo {
  display: grid;
  gap: 2rem;
}

.performance-controls {
  background: white;
  padding: 1.5rem;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.control-group {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1rem;
}

.control-group label {
  font-weight: 600;
  color: #374151;
  min-width: 100px;
}

.slider {
  flex: 1;
  max-width: 200px;
}

.button-group {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
}

.performance-results {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.result-card {
  background: white;
  padding: 1.5rem;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.result-card h4 {
  margin: 0 0 1rem 0;
  color: #374151;
}

.result-card p {
  margin: 0.5rem 0;
  color: #64748b;
}

.improvement {
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid #e2e8f0;
}

.improvement-text {
  color: #059669;
  font-weight: 600;
}

.use-cases {
  display: grid;
  gap: 2rem;
}

.use-case {
  background: white;
  padding: 1.5rem;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.use-case h4 {
  margin: 0 0 0.5rem 0;
  color: #374151;
}

.use-case > p {
  color: #64748b;
  margin-bottom: 1rem;
}

.demo-area {
  display: grid;
  gap: 1rem;
}

.demo-area .controls {
  flex-direction: row;
  flex-wrap: wrap;
}

.data-info,
.external-state {
  background: #f8fafc;
  padding: 1rem;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
}

.data-info p,
.external-state p {
  margin: 0.25rem 0;
  color: #374151;
}

.best-practices {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1.5rem;
}

.practice-section {
  background: white;
  padding: 1.5rem;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.practice-section h4 {
  margin: 0 0 1rem 0;
  color: #374151;
}

.practice-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.practice-list li {
  padding: 0.5rem 0;
  border-bottom: 1px solid #f1f5f9;
  position: relative;
  padding-left: 1.5rem;
}

.practice-list li:last-child {
  border-bottom: none;
}

.practice-list.good li::before {
  content: "✅";
  position: absolute;
  left: 0;
}

.practice-list.bad li::before {
  content: "❌";
  position: absolute;
  left: 0;
}

.practice-list.tips li::before {
  content: "💡";
  position: absolute;
  left: 0;
}

.practice-list.good {
  border-left: 4px solid #10b981;
}

.practice-list.bad {
  border-left: 4px solid #ef4444;
}

.practice-list.tips {
  border-left: 4px solid #f59e0b;
}

@media (max-width: 768px) {
  .comparison-container {
    grid-template-columns: 1fr;
  }

  .performance-results {
    grid-template-columns: 1fr;
  }

  .button-group {
    flex-direction: column;
  }

  .demo-area .controls {
    flex-direction: column;
  }

  .best-practices {
    grid-template-columns: 1fr;
  }
}
</style>
